package com.stan.common;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 字符串拼接工具类
 * @author Administrator
 *
 */
public class ConcatStrUtils {

	/**
	 * 以separator分隔符进行trim,也就是去掉字符串两端任意数量的分隔符
	 * @param concatStr
	 * @param separator
	 * @return
	 */
	public static String trimSeqarator(String concatStr, String separator){
		// 去头
		while(concatStr.startsWith(separator)){
			concatStr = concatStr.substring(1);
		}
		// 洽尾
		while(concatStr.endsWith(separator)){
			concatStr = concatStr.substring(0,concatStr.length()-1);
		}
		return concatStr;
	}

	/**
	 * 将KV对拼接进去
	 * @param concatStr
	 * @param separator
	 * @param key
	 * @param value
	 * @return
	 */
	public static String addFieldFromConcatStr(String concatStr,String separator,String key, String value) {
		concatStr += separator + key + "=" + value;
		return concatStr;
	}

	/**
	 * 从拼接字符串中依据相应的key获得相应的value
	 * @param key
	 * @return
	 */
	public static String getFieldFromConcatStr(String concatStr, String separator, String key){
		Map<String,String> map = concatStrToMap(concatStr,separator);
		String value = map.get(key);
		return value;
	}




	/**
	 * 将 (k1,v1), (k2,v2) ... 转成 k1=v1|k2=v2状态
	 * @param map
	 * @param separator 分隔符
	 * @return
	 */
	public static String mapToConcatStr(Map<String,String> map, String separator){
		StringBuffer sb = new StringBuffer();
		int i = 0 ;
		Iterator<String> keyIterator = map.keySet().iterator();
		while(keyIterator.hasNext()){
			String key = keyIterator.next();
			String value = map.get(key);
			i++;
			sb.append(key+"="+value);
			if(i != map.size()){
				sb.append(separator);
			}
		}
		return sb.toString();
	}

	/**
	 * 将拼接字符串转成Map KV对
	 * @param composite
	 * @param separator 分隔符
	 * @return
	 */
	public static Map<String,String> concatStrToMap(String composite, String separator){
		Map<String,String> map = new HashMap<String,String>();
		if(separator == "|") {
			separator = "\\|";
		}
		String[] kvs = composite.split(separator);
		for(String kv : kvs) {
			String[] k2v = kv.split("=");
			if(k2v.length>=2){
				map.put(k2v[0],k2v[1]);
			}
		}
		return map;
	}

}
